﻿namespace Sgr.AspNetCore.Middlewares.RequestRoute
{
    /// <summary>
    /// 中间件：从请求中读取标识（header 或 query）并设置 RequestRouteContext.ForceUseMaster
    /// header 名称：X-Force-Master
    /// query 参数：forceMaster=true
    /// 注意：在生产中应对触发权限做校验，避免被外部滥用。
    /// </summary>
    public class RequestRouteMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestRouteMiddleware(RequestDelegate next)
        {
            _next = next ?? throw new ArgumentNullException(nameof(next));
        }

        public async Task InvokeAsync(HttpContext context, IRequestRouteContext routeContext)
        {
            ArgumentNullException.ThrowIfNull(context);

            var force = false;

            if ((context.Request.Headers.TryGetValue("X-Force-Master", out var headerValues) && HasForceMasterFlag(headerValues))
                || (context.Request.Query.TryGetValue("forceMaster", out var queryValues) && HasForceMasterFlag(queryValues)))
            {
                force = true;
            }

            // 可在此增加权限校验，例如只允许内部网段/已认证用户/特定角色设置该标志
            routeContext.ForceUseMaster = force;

            await _next(context);
        }

        private static bool HasForceMasterFlag(Microsoft.Extensions.Primitives.StringValues values)
        {
            if (values.Count == 0) return false;

            // 只接受明确的允许值，避免单纯存在 header 即视为 true
            var trueValues = new[] { "1", "true" };
            foreach (var v in values)
            {
                if (string.IsNullOrWhiteSpace(v)) continue;
                var s = v.Trim();
                if (trueValues.Any(x => x.Equals(s, StringComparison.OrdinalIgnoreCase)))
                    return true;
            }
            return false;
        }
    }
}